package servlets;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cmput391.src.queries.*;

/**
 * Servlet implementation class EditMyInfo
 */
@WebServlet("/ProcessUpdatePassword")
public class ProcessUpdatePassword extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProcessUpdatePassword() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Messages go in here
		Map<String, String> messages = new HashMap<String, String>();
		
		String password = (request.getParameter("password")).trim();
		String password2 = (request.getParameter("password2")).trim();		
		String username = (request.getParameter("username")).trim();
		
		request.setAttribute("messages", messages);
		request.setAttribute("password", password);		
		
		if (password.equals(password2)) {
			
			DBConnector dbConnect = new DBConnector();
			SecurityQueries security = null;
			
			try {
				security = new SecurityQueries(dbConnect.getConnection());
				UserQueries uq = new UserQueries(dbConnect.getConnection(), security);
				uq.updatePassword(username, password);	
				messages.put("message", "<span class=\"message success\">Password updated.</span>");
				
				request.getRequestDispatcher("UpdateProfile").forward(request, response);		
			}
			catch (Exception e) {
			      e.printStackTrace();
			      messages.put("message", "<span class=\"message error\">There was an error while updating your password.</span>");
			      request.getRequestDispatcher("UpdateProfile").forward(request, response);			      
			}
		}
		else {
			messages.put("message", "<span class=\"message error\">Passwords don't match.</span>");
			request.getRequestDispatcher("UpdateProfile").forward(request, response);
		}
	}

}
